<?php
include('includes/connection_settings.php');

//Strips " and ' marks
$bannedMarks = array("\"", "'");

$_GET['username'] = str_replace($bannedMarks, "", $_GET['username']);
$_GET['password'] = str_replace($bannedMarks, "", $_GET['password']);

$_GET['username'] = str_replace(" ", "_", $_GET['username']);
$_GET['username'] = str_replace("|", "", $_GET['username']);


//checks if there is forhibben characters in username
$table = wordwrap($_GET['username'], 1, "|", 1);
$table = explode("|", $table);

for ($i = 0; $i < count($table); $i++) {
 $ascii = ord($table[$i]);

 if ($ascii <= 64) {
  echo "invalid username";
  exit;
 }

 elseif ($ascii >= 91 AND $ascii <= 96) {
  echo "invalid username";
  exit;
 }

 elseif ($ascii >= 123) {
  echo "invalid username";
  exit;
 }
}

//How many users
$table = mysql_query("SELECT COUNT(*) FROM users");
$userCount = mysql_result($table, 0, 0);

//Check if username already exists
$table = mysql_query("SELECT username FROM users");

for ($i = 0; $i < $userCount; $i++) {
 if (strtolower(mysql_result($table, $i, 0)) == strtolower($_GET['username']) OR $_GET['username'] == "Username in use!") {
  echo "<h1>Username already exists!</h1><p>Please, choose another username</p>";
  exit;
 }
}

//adds point_username -column
if (!mysql_query("ALTER TABLE words ADD points_{$_GET['username']} INT(2) DEFAULT '0'")) {
 echo "<h1>warning: Can't alter the table!</h1><p>" . mysql_error($connection) . "</p>";
}

//If first one, makes it admin
$table = mysql_query("SELECT * FROM users");

if (mysql_result($table, 0, 0) == "") {
 if (!mysql_query("INSERT INTO users (username, usernamePlusPassword, startingLanguage, wordCount, admin) VALUES ('{$_GET['username']}', '" . md5($_GET['username'] . $_GET['password']) . "', 'mix', 1, true)")) {
  echo "<h1>Can't add data to the table!</h1><p>" . mysql_error($connection) . "</p>";
  exit;
 }
}

else {
 if (!mysql_query("INSERT INTO users (username, usernamePlusPassword, startingLanguage, wordCount, admin) VALUES ('{$_GET['username']}', '" . md5($_GET['username'] . $_GET['password']) . "', 'mix', 1, false)")) {
  echo "<h1>Can't add data to the table!</h1><p>" . mysql_error($connection) . "</p>";
  exit;
 }
}

//add username to the choices table
if (!mysql_query("ALTER TABLE choices ADD {$_GET['username']} BOOLEAN DEFAULT false")) {
 echo "<h1>warning: Can't alter the table!</h1><p>" . mysql_error($connection) . "</p>";
}

echo "true";

?>